/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Core;

import java.io.PrintStream;
import java.util.Vector;

/**
 *
 * @author Mr Bao
 */
public class WriterThread extends Thread {

    private boolean isRunning = true;
    private Vector outgoingMessage;
    private PrintStream out;
    private long delayTime = 1000L;

    public WriterThread(PrintStream out) {
        this.outgoingMessage = new Vector();
        this.out = out;
    }

    public void FlushOutputQueue() {
        while (outgoingMessage.size() > 0) {
            String message = (String) outgoingMessage.elementAt(0);
            outgoingMessage.removeElementAt(0);
            out.println(message);
        }
        out.flush();
    }

    public synchronized void QueueMessage(String s) {
        outgoingMessage.add(s);
        notify();
    }

    @Override
    public void run() {
        while (isRunning) {
            try {
                FlushOutputQueue();
                wait(delayTime);
            } catch (InterruptedException ex) {
            }
        }
    }

    public void Halt() {
        isRunning = false;
    }
}
